package com.yicong.ants.ui.scenic;

import android.app.AlertDialog;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.util.Pair;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.cchao.simplelib.Const;
import com.cchao.simplelib.core.AndroidHelper;
import com.cchao.simplelib.core.CollectionHelper;
import com.cchao.simplelib.core.JsonHelper;
import com.cchao.simplelib.core.Logs;
import com.cchao.simplelib.core.Router;
import com.cchao.simplelib.core.RxHelper;
import com.cchao.simplelib.core.UiHelper;
import com.cchao.simplelib.model.event.CommonEvent;
import com.cchao.simplelib.ui.activity.BaseStatefulActivity;
import com.cchao.simplelib.ui.adapter.DataBindQuickAdapter;
import com.cchao.simplelib.ui.web.WebViewActivity;
import com.cchao.simplelib.util.CallBacks;
import com.cchao.simplelib.util.StringHelper;
import com.wdullaer.materialdatetimepicker.date.DatePickerDialog;
import com.yicong.ants.BR;
import com.yicong.ants.Constants;
import com.yicong.ants.R;
import com.yicong.ants.bean.scenic.AddedItem;
import com.yicong.ants.bean.scenic.ScenicDetailBean;
import com.yicong.ants.bean.scenic.WeatherBean2;
import com.yicong.ants.databinding.DialogJoinAddedBinding;
import com.yicong.ants.databinding.ItemScenicDetailAddedBinding;
import com.yicong.ants.databinding.ScenicDetailConfigActivityBinding;
import com.yicong.ants.manager.BusinessHelper;
import com.yicong.ants.manager.UserManager;
import com.yicong.ants.manager.ad.AntsAdHelper;
import com.yicong.ants.manager.business.Dialogs;
import com.yicong.ants.manager.config.ZzConfigs;
import com.yicong.ants.manager.http.RetrofitHelper;
import com.yicong.ants.ui.me.UserInfoActivity;
import com.yicong.ants.ui.order.BillHistoryTabActivity;
import com.yicong.ants.utils.AmapHelper;
import com.yicong.ants.utils.AppUtils;
import com.yicong.ants.utils.StringUtils;
import com.yicong.ants.utils.TimeHelper;
import com.yicong.ants.view.popup.CommonSharePopup;

import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import io.reactivex.Observable;


/**
 * 景区详情页面
 * 景区类型  scenic_type ：10：特惠景区，25 中食，20 云南，30 免预约景区
 *
 * @author cchao
 */
public class ScenicDetailConfigActivity extends BaseStatefulActivity<ScenicDetailConfigActivityBinding> implements View.OnClickListener {
    TextView mApply;

    String mScenicId;
    ScenicDetailBean mDetailBean;

    @Override
    protected int getLayout() {
        return R.layout.scenic_detail_config_activity;
    }

    @Override
    protected void initEventAndData() {
        mDataBind.setClick(this);
        //实现侧滑菜单状态栏透明
        if (AndroidHelper.versionThanM()) {
            getWindow().setStatusBarColor(UiHelper.getColor(R.color.transparent));
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }

//        UiHelper.setDeleteLine(mDataBind.chargePrice);
        UiHelper.setVisibleElseGone(mDataBind.collect, ZzConfigs.mGlobalCollectFeature);
//        UiHelper.setVisibleElseGone(mDataBind.tvCollect, ZzConfigs.mGlobalCollectFeature);

        mScenicId = getIntent().getStringExtra(Constants.Extra.Id);

        mApply = mDataBind.apply;
        onLoadData();
        loadAd();
        mDataBind.adViewTimer.startTime(mDisposable);
    }

    private void loadAd() {
        UiHelper.setVisibleElseGone(mDataBind.adContainer, false);

        Map<String, String> map = new HashMap<>();
        map.put("position", AntsAdHelper.Position.scenic_product_banner);
        addSubscribe(RetrofitHelper.getApis().adBanner(map)
            .compose(RxHelper.toMain())
            .subscribe(respBean -> {
                hideProgress();
                if (respBean.isCodeFail() || respBean.getData() == null) {
                    return;
                }
                View imageView = AntsAdHelper.getAdBanner(thisActivity, respBean.getData());
                mDataBind.adContainer.addView(imageView);
                UiHelper.setVisibleElseGone(mDataBind.adContainer, true);
                AntsAdHelper.exposeAd(respBean.getData().getAd_id());
            }, RxHelper.getHideProgressConsumer(this)));
    }

    @Override
    protected void onLoadData() {
        switchView(LOADING);
        Map<String, String> map = new HashMap<>();
        map.put("scid", mScenicId);
        map.put("scenic_id", mScenicId);
//        map.put("scenic_type", mScenicType);
        if (StringHelper.isNotEmpty(getIntent().getStringExtra(Constants.Extra.Search))) {
            map.put("search_name", getIntent().getStringExtra(Constants.Extra.Search));
        }
        addSubscribe(RetrofitHelper.getApis().getScenicDetail(map)
            .compose(RxHelper.toMain())
            .subscribe(respBean -> {
                if (respBean.isCodeFail()) {
                    showToast(respBean.getMsg());
                    switchView(NET_ERROR);
                    return;
                }
                switchView(CONTENT);
                mDetailBean = respBean.getData();
                updateDetail(mDetailBean);
                loadWeather();
            }, RxHelper.getSwitchErrorConsumer(this)));
    }

    @Override
    public void onEvent(CommonEvent event) {
        super.onEvent(event);
        switch (event.getCode()) {
            case Constants.Event.Meitu_Bind_Suc:
                break;
        }
    }

    private void updateDetail(ScenicDetailBean bean) {
        mDataBind.setBean(bean);
        if (StringHelper.isNotEmpty(bean.getDetail())) {
            addSubscribe(Observable.just(bean.getDetail())
                .map(StringHelper::forHtml)
                .compose(RxHelper.toMain())
                .subscribe(spanned -> {
                    //
                    mDataBind.detail.setText(spanned);
                    mDataBind.detail.invalidate();
                }));
        }

        if (StringHelper.isNotEmpty(bean.getTraffic())) {
            mDataBind.traffic.setText(Html.fromHtml(bean.getTraffic()));
        }

        if (StringHelper.isNotEmpty(bean.getContained_items())) {
            mDataBind.containedItems.setText(Html.fromHtml(bean.getContained_items()));
        }
        updateApplyType();
//        updateCanBuy(bean.getIs_buy() == 1);
        updateCollect();
//        updateWeather();
        updateAdded();
//        updateDiscount();
    }

    private void loadWeather() {
        // 判空
        if (StringHelper.isEmpty(mDetailBean.getLongitude()) || "null".equals(mDetailBean.getLongitude())) {
            UiHelper.setVisibleElseGone(mDataBind.weatherField, false);
            return;
        }
        Map<String, String> params = new HashMap<>(4);
        params.put("location", mDetailBean.getLongitude() + "," + mDetailBean.getLatitude());
        addSubscribe(RetrofitHelper.getApis().getWeather(params)
            .compose(RxHelper.toMain())
            .subscribe(respBean -> {
                hideProgress();
                if (respBean.isCodeFail()) {
//                    showToast(respBean.getMsg());
                    UiHelper.setVisibleElseGone(mDataBind.weatherField, false);
                    return;
                }
                mDetailBean.setWeather(respBean.getData());
                updateWeather();
            }, throwable -> {
                UiHelper.setVisibleElseGone(mDataBind.weatherField, false);
                Logs.logException(throwable);
            }));
    }

    /**
     * 二次消费项目
     */
    private void updateAdded() {
        UiHelper.setVisibleElseGone(mDataBind.addedItemField, CollectionHelper.isNotEmpty(mDetailBean.getAdded_projects()));
        UiHelper.setVisibleElseGone(mDataBind.addedEmpty, CollectionHelper.isEmpty(mDetailBean.getAdded_projects()));

        if (mDetailBean.getAdded_projects() != null) {
            for (AddedItem addedItem : mDetailBean.getAdded_projects()) {
                ItemScenicDetailAddedBinding binding = DataBindingUtil.inflate(mLayoutInflater
                    , R.layout.item_scenic_detail_added, mDataBind.addedFlex, false);
                binding.setBean(addedItem);
                binding.getRoot().setOnClickListener(v -> {
                    //
                    Router.turnTo(mContext, AddedDetailActivity.class)
                        .putExtra(Constants.Extra.JSON, JsonHelper.toJson(addedItem))
                        .putExtra(Constants.Extra.JSON2, JsonHelper.toJson(mDetailBean))
                        .start();
                });
                mDataBind.addedFlex.addView(binding.getRoot());
            }
            // 查看更多  大于6个才显示
            UiHelper.setVisibleElseGone(mDataBind.addedMore, mDetailBean.getAdded_projects().size() > 6);
            if (mDetailBean.getAdded_projects().size() <= 3) {
                mDataBind.addedFlex.getLayoutParams().height = UiHelper.dp2px(116);
                mDataBind.addedFlex.requestLayout();
            }
        }
    }

    private void updateCollect() {
        boolean toggle = mDetailBean.getIs_collect() == 1;
        Drawable drawable = UiHelper.getDrawable(toggle ? R.drawable.icon_collect_true : R.drawable.scenic_detail_collect_bottom_default);
        drawable.setBounds(0, 0, UiHelper.dp2px(22), UiHelper.dp2px(22));
        int collectDrawable = toggle ? R.drawable.scenic_detail_collect_pressed : R.drawable.scenic_detail_collect_default;
        mDataBind.collect.setCompoundDrawables(null, drawable, null, null);
    }

    /**
     * 加载天气信息
     */
    private void updateWeather() {
        if (CollectionHelper.isEmpty(mDetailBean.getWeather())) {
            return;
        }
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mDataBind.rcWeather.setLayoutManager(layoutManager);
        mDataBind.rcWeather.setAdapter(new DataBindQuickAdapter<WeatherBean2>(R.layout.scenic_weather_item, mDetailBean.getWeather()) {
            @Override
            protected void convert(DataBindViewHolder helper, WeatherBean2 item) {
                helper.getBinding().setVariable(BR.bean, item);
            }
        });

        mDataBind.rcWeather.addItemDecoration(new DividerItemDecoration(mContext, DividerItemDecoration.HORIZONTAL) {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                int adapterPosition = parent.getChildAdapterPosition(view);
                outRect.left = UiHelper.dp2px(13);
                if (adapterPosition == 0) {
                    outRect.left = UiHelper.dp2px(12);
                }
            }
        });
    }

    /**
     * 初始化日历选择器
     */
    private void showAppointDatePicker(String startDate, CallBacks.Str callBack) {
        DatePickerDialog.OnDateSetListener listener = (view, year, monthOfYear, dayOfMonth) -> {
            String mon, day;
            ++monthOfYear;
            mon = monthOfYear < 10 ? "0" + monthOfYear : String.valueOf(monthOfYear);
            day = dayOfMonth < 10 ? "0" + dayOfMonth : String.valueOf(dayOfMonth);

            String time = year + "-" + mon + "-" + day;
            if (null == UserManager.getUserBean()) {
                showToast("请先登录");
                return;
            }
            callBack.onCallBack(time);
        };

        String format = "yyyy-MM-dd";

        Calendar calendar = Calendar.getInstance();
        Date date = null;
        try {
            date = new Date(TimeHelper.formatToStamp(startDate, format));
            calendar.setTime(date);
        } catch (Exception e) {
            Logs.logException(e);
        }

        DatePickerDialog dpd = DatePickerDialog.newInstance(listener,
            calendar.get(Calendar.YEAR),
            calendar.get(Calendar.MONTH),
            calendar.get(Calendar.DAY_OF_MONTH)
        );
        dpd.setThemeDark(false);
        dpd.vibrate(true);
        dpd.dismissOnPause(false);
        dpd.showYearPickerFirst(false);
        dpd.setVersion(DatePickerDialog.Version.VERSION_1);
        dpd.setAccentColor(ContextCompat.getColor(this, R.color.appColor));
        dpd.setTitle("游玩时间");
        dpd.show(getFragmentManager(), "Datepickerdialog");
    }

    /**
     * 预定景区
     */
    void orderScenicTime(String time) {
        Map<String, String> map = new HashMap<>();
        map.put("type", "advance_scenic");
        map.put("pre_coin", String.valueOf(mDetailBean.getCoin()));
        addSubscribe(RetrofitHelper.getApis().consume_detail(map)
            .compose(RxHelper.toMain())
            .subscribe(respBean -> {
                hideProgress();
                if (respBean.isCodeFail()) {
                    showToast(respBean.getMsg());
                    return;
                }

                // 显示预约详情
                Dialogs.showConsumeDetail(mContext, Pair.create(mDetailBean.getName(), time), respBean.getData(), () -> {

                    Map<String, String> params = new HashMap<>();
                    params.put("scenic_id", mScenicId);
                    params.put("visit_date", time);
                    onAdvanceScenic(params);

                });
            }, RxHelper.getHideProgressConsumer(this)));
    }

    void onAdvanceScenic(Map<String, String> params) {
        showProgress();
        addSubscribe(RetrofitHelper.getApis().orderScenic(params)
            .compose(RxHelper.toMain())
            .subscribe(respBean -> {
                hideProgress();
                if (respBean.isCodeFail()) {
                    UiHelper.showLongToast(respBean.getMsg());
                    UserManager.checkAuthRouter(mContext, respBean);
                    return;
                }
                UiHelper.showLongToast(respBean.getMsg());
                Router.turnTo(mContext, BillHistoryTabActivity.class)
                    .putExtra(Constants.Extra.Index, 0)
                    .start();
            }, RxHelper.getHideProgressConsumer(this)));
    }

    private void updateApplyType() {
        mDataBind.applyField.setBackgroundResource(R.drawable.apply_theme_bg);
        UiHelper.setVisibleElseGone(mDataBind.advanceCoinTip, false);
        switch (mDetailBean.getScenic_type()) {
            case Constants.Scenic_Type.AdvanceScenic:
            case Constants.Scenic_Type.DiscountScenic:
            case Constants.Scenic_Type.PartnerScenic:
                String tip = BusinessHelper.getScenicCanUseCoin(mDetailBean.getScenic_type());
                mDataBind.advanceCoinTip.setText(tip);
                UiHelper.setVisibleElseGone(mDataBind.advanceCoinTip, UserManager.isLogin() && StringHelper.isNotEmpty(tip));
                mApply.setText(mDetailBean.getCoin() + " 门票游玩");
                break;
            case Constants.Scenic_Type.FreeScenic:
                mApply.setText("无门票景区");
                mDataBind.applyField.setBackgroundResource(R.drawable.shape_details_scenic_spot_btn_false);
                mApply.setTextColor(UiHelper.getColor(R.color.txt_gray_7));
                break;
            case Constants.Scenic_Type.PowerlessScenic:
                mApply.setText("线下购票入园");
                mDataBind.applyField.setBackgroundResource(R.drawable.shape_details_scenic_spot_btn_false);
                mApply.setTextColor(UiHelper.getColor(R.color.txt_gray_7));
                break;
            default:
                mDataBind.applyField.setBackgroundResource(R.drawable.shape_details_scenic_spot_btn_false);
                mApply.setTextColor(UiHelper.getColor(R.color.txt_gray_7));
                mApply.setText(UiHelper.getString(R.string.no_need_to_make_an_appointment));
                break;
        }
    }

    private void apply() {
        // 未认证
        if (UserManager.isNotAuthElseTurn(mContext)) {
            return;
        }

        switch (mDetailBean.getScenic_type()) {
            // 预约景区
            case Constants.Scenic_Type.AdvanceScenic:
            case Constants.Scenic_Type.DiscountScenic:
                // 选择日期
                showAppointDatePicker(mDetailBean.getAdvance_start_date(), str -> {
                    try {
                        orderScenicTime(str);
                    } catch (Exception ex) {
                        Logs.logException(ex);
                        UiHelper.showToast(str);
                    }
                });
                break;
            // 免预约
            case Constants.Scenic_Type.PartnerScenic:
                if (UserManager.getUserBean().getCoin_float() < mDetailBean.getCoin()) {
                    showToast("门票不足");
                    return;
                }
                UiHelper.showCancelDialog(mContext, "确定使用门票兑换游玩？", Pair.create("确定", (dialogInterface, i) -> {
                    showProgress();
                    addSubscribe(RetrofitHelper.getApis().getTicketCode(Collections.emptyMap())
                        .compose(RxHelper.toMain())
                        .subscribe(respBean -> {
                            hideProgress();
                            if (respBean.isCodeFail()) {
                                showToast(respBean.getMsg());
                                UserManager.checkAuthRouter(mContext, respBean);
                                return;
                            }
                            ZzConfigs.toWebActivityCheckLogin(mContext, "入园码", respBean.getData().getTicket_url());
                            dialogInterface.dismiss();
                        }, RxHelper.getHideProgressConsumer(this)));
                }), Pair.create("取消", (dialogInterface, i) -> {
                    dialogInterface.dismiss();
                }));
                break;
            case Constants.Scenic_Type.FreeScenic:
                UiHelper.showConfirmDialog(mContext, "该景区无需购票即可入园", null);
                break;
            case Constants.Scenic_Type.PowerlessScenic:
                UiHelper.showConfirmDialog(mContext, "该景区不提供线上电子门票\n需购买线下实体门票,凭门票入园", null);
                break;
        }
    }

    /**
     * 收藏按钮点击
     */
    private void toggleCollection() {
        if (UserManager.isNotLoginElseTurn(mContext)) {
            return;
        }

        showProgress();
        UserManager.toggleCollect(mDetailBean.getIs_collect() == 0, mScenicId, () -> {
            hideProgress();
            mDetailBean.setIs_collect(Math.abs(mDetailBean.getIs_collect() - 1));
            updateCollect();
        });
    }

    boolean checkInputFail(EditText editText, String toast) {
        if (StringHelper.isEmpty(editText)) {
            showToast(toast);
            return true;
        }
        return false;
    }

    /**
     * 加盟项目
     */
    private void showDialogAddedJoin() {
        DialogJoinAddedBinding binding = DataBindingUtil.inflate(mLayoutInflater, R.layout.dialog_join_added, null, false);
        if (UserManager.isLogin()) {
            binding.mobile.setText(UserManager.getMobile());
        }
        new AlertDialog.Builder(mContext)
            .setView(binding.getRoot())
            .setPositiveButton("提交加盟信息", (dialo, which) -> {
                if (checkInputFail(binding.name, "请输入姓名")) {
                    return;
                }
                if (checkInputFail(binding.mobile, "请输入手机号")) {
                    return;
                }
                if (checkInputFail(binding.describe, "请输入项目描述")) {
                    return;
                }

                Map<String, String> map = new HashMap<>();
                map.put("scenic_name", mDetailBean.getName());
                map.put("scenic_id", mDetailBean.getScenic_id());
                map.put("describe", binding.describe.getText().toString());
                map.put("user_name", binding.name.getText().toString());
                map.put("mobile", binding.mobile.getText().toString());
                showProgress();
                addSubscribe(RetrofitHelper.getApis().simpleApi("/Scenic/join_added", map)
                    .compose(RxHelper.toMain())
                    .subscribe(respBean -> {
                        hideProgress();
                        showToast(respBean.getMsg());
                        dialo.dismiss();
                    }, RxHelper.getHideProgressConsumer(this)));
            }).show();
    }

    @Override
    public void onClick(View v) {
        String tel = UiHelper.getString(R.string.app_tel);
        if (StringHelper.isNotEmpty(mDetailBean.getTelephone())) {
            tel = mDetailBean.getTelephone();
        }

        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.collect:
                toggleCollection();
                break;
            case R.id.share:
                if (mDetailBean == null) {
                    return;
                }

                // 链接参数中的v标识为景区id
                //如: ants://platform/app?id=11081&v=1023456
                String link = "ants://platform/app?id=11081&v=" + mScenicId;

                new CommonSharePopup(thisActivity)
                    .setTitle(mDetailBean.getName(), link)
                    .showPopupWindow(v);

                break;
            case R.id.read_more:
                if (StringUtils.isNull(mDetailBean.getVr_url())) {
                    showToast("视频介绍暂无");
                    return;
                }
                Router.turnTo(mContext, WebViewActivity.class)
                    .putExtra(Const.Extra.Web_View_Url, mDetailBean.getVr_url())
                    .putExtra(Const.Extra.Web_View_Tile, mDetailBean.getName())
                    .start();
                break;
            case R.id.added_join:
                showDialogAddedJoin();
                break;
            case R.id.address_field:
                PopupWindow mMapPopup = AmapHelper.showNavigatePop(mContext, mDetailBean);
                mMapPopup.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
                break;
            case R.id.customer_server:
                AppUtils.jumpToTel(this, tel);
                break;
            case R.id.apply_field:
                if (UserManager.isNotLoginElseTurn(mContext)) {
                    return;
                }
                if (!UserManager.getUserBean().getIsAuth()) {
                    showToast("您还没实名认证");
                    Router.turnTo(mContext, UserInfoActivity.class).start();
                    return;
                }
                apply();
                break;
            case R.id.dr_go_top:
                // nestedScrollView.scrollTo(0, 0);
                break;
            case R.id.added_more:
                Router.turnTo(mContext, AddedProjectListActivity.class)
                    .putExtra(Constants.Extra.JSON, JsonHelper.toJson(mDetailBean))
                    .start();

         /*       int height = mDataBind.addedMore.getText().equals("查看全部") ? ViewGroup.LayoutParams.WRAP_CONTENT : UiHelper.dp2px(120);
                String text = mDataBind.addedMore.getText().equals("收起") ? "查看全部" : "收起";
                mDataBind.addedFlex.getLayoutParams().height = height;
                mDataBind.addedFlex.requestLayout();
                mDataBind.addedMore.setText(text);*/
                break;
        }
    }
}
